package com.boot.mall.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.boot.common.utils.R;
import com.boot.common.vo.MemberResponseVo;
import com.boot.mall.auth.feign.MemberRegisterFeignService;
import com.boot.mall.auth.service.AuthService;
import com.boot.mall.auth.utils.HttpUtils;
import com.boot.mall.auth.vo.SocialUser;
import com.boot.mall.auth.vo.WeiBoUserInfoVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {

    @Value("${weibo.auth.app-key}")
    private String appKey;
    @Value("${weibo.auth.app-secret}")
    private String appSecret;
    @Value("${weibo.auth.redirect-uri}")
    private String redirectUri;

    private static String apiHost = "https://api.weibo.com";

    @Autowired
    private MemberRegisterFeignService memberRegisterFeignService;

    /**
     * 获取用户授权页的地址
     * @return
     */
    @Override
    public String getWeiBoAuthUrl() {
        String baseUrl = "https://api.weibo.com/oauth2/authorize";
        String clientId = "?client_id=" + appKey;
        String responseType = "&response_type=code";
        String redirectUrl = "&redirect_uri=" + redirectUri;
        String url = baseUrl + clientId + responseType + redirectUrl;
        return url;
    }

    /**
     * 根据用户的授权码请求token
     * @return
     * @param code
     */
    @Override
    public SocialUser getUserToken(String code) throws Exception {
        // 请求头参数
        Map<String,String> headers = new HashMap<>();
        // 请求体参数
        Map<String,String> body = new HashMap<>();
        body.put("client_id", appKey);
        body.put("client_secret", appSecret);
        body.put("grant_type", "authorization_code");   //授权方式
        body.put("redirect_uri", redirectUri);
        body.put("code", code);

        // 带着用户的授权码去微博资源服务器请求用户信息的token值
        HttpResponse response = HttpUtils.doPost(apiHost, "/oauth2/access_token", "post", headers, null, body);

        if (response.getStatusLine().getStatusCode() == 200){
            // 获取返回结果
            String responseJson = EntityUtils.toString(response.getEntity());
            // 封装成社交登录对象返回
            SocialUser socialUser = JSON.parseObject(responseJson, SocialUser.class);
            return socialUser;
        }
        return null;
    }

    /**
     * 根据用户的token值查询微博用户的基本信息
     * @param userToken
     * @return
     */
    @Override
    public MemberResponseVo getUserInfoByToken(SocialUser userToken) throws Exception {
        /**
         * 登录流程应该是：
         *      拿到用户的uid和token之后，首先根据用户的uid查询数据库
         *      当用户不存在时，根据用户的token值获取用户的基本信息，再进行注册
         *      当用户存在时，直接调用登录方法即可
         */
        //请求的接口地址
        //https://api.weibo.com/2/users/show.json?access_token=2.00rsTWBIurqVnB5fc7ad66490MDZYu&uid=7351580365

        // 根据用户的uid查询数据库中是否存在该用户
        String uid = userToken.getUid();
        ObjectMapper mapper = new ObjectMapper();

        R res = memberRegisterFeignService.getMemberInfo(uid);

        // 当前微博登录用户存在，调用登录方法即可
        MemberResponseVo responseVo = null;
        if (res.get("member") != null) {
            Object object = res.get("member");
            responseVo = mapper.convertValue(object,MemberResponseVo.class);
            return responseVo;
        }

        // 当前微博用户未注册，调用微博api查询用户的信息，调用注册方法

        // 请求头参数
        Map<String,String> headers = new HashMap<>();
        // 构建请求体参数
        Map<String,String> query = new HashMap<>();
        query.put("access_token", userToken.getAccess_token());
        query.put("uid", uid);

        // 请求用户基本信息
        HttpResponse response = HttpUtils.doGet(apiHost, "/2/users/show.json", "get", headers, query);
        // 请求成功
        if (response.getStatusLine().getStatusCode() == 200){

            String userInfoJson = EntityUtils.toString(response.getEntity());
            // 将微博用户信息封装

            WeiBoUserInfoVo userInfoVo = JSON.parseObject(userInfoJson,WeiBoUserInfoVo.class);

            MemberResponseVo member = new MemberResponseVo();

            member.setUid(uid);
            member.setUsername(userInfoVo.getName());
            member.setNickname(userInfoVo.getScreen_name());

            // 调用远程接口第三方登录
            R result = memberRegisterFeignService.weiBoUserAuthRegister(member);

            MemberResponseVo loginMember = mapper.convertValue(result.get("member"), MemberResponseVo.class);
            return loginMember;
        }
        return null;
    }
}
